'''
链表相加：
从低位到高位，计算，如果有进位，下次计算时+1.
注意条件，l1和l2，以及有进位都要进行计算。
'''
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode:
    dummy = ListNode()
    current = dummy
    carry = 0

    while l1 or l2 or carry:
        val1 = l1.val if l1 else 0
        val2 = l2.val if l2 else 0

        print(f"val1: {val1}, val2:{val2}")

        # 计算当前位的和
        total = val1 + val2 + carry
        print(f"total: {total}, carry:{carry}")

        # 计算是否有进位，用于下次计算
        carry = total // 10
        # 取余数
        current_digit = total % 10

        print(f"current_digit: {current_digit}, carry:{carry}")

        # 创建新节点
        current.next = ListNode(current_digit)
        current = current.next

        # 移动指针
        if l1:
            l1 = l1.next
        if l2:
            l2 = l2.next

    return dummy.next

# 辅助函数：创建链表
def createList(values):
    if not values:
        return None
    head = ListNode(values[0])
    current = head
    for value in values[1:]:
        current.next = ListNode(value)
        current = current.next
    return head

# 辅助函数：打印链表
def printList(node: ListNode):
    while node:
        print(node.val, end=" -> ")
        node = node.next
    print("None")

# 测试用例
def test_addTwoNumbers():
    # 测试用例 1
    l1 = createList([2, 4, 3])
    l2 = createList([5, 6, 4])
    result1 = addTwoNumbers(l1, l2)
    print("Test case 1:")
    printList(result1)  # 预期输出: 7 -> 0 -> 8 -> None

    # 测试用例 2
    l1 = createList([0])
    l2 = createList([0])
    result2 = addTwoNumbers(l1, l2)
    print("Test case 2:")
    printList(result2)  # 预期输出: 0 -> None

    # 测试用例 3
    l1 = createList([9, 9, 9, 9, 9, 9, 9])
    l2 = createList([9, 9, 9, 9])
    result3 = addTwoNumbers(l1, l2)
    print("Test case 3:")
    printList(result3)  # 预期输出: 8 -> 9 -> 9 -> 9 -> 0 -> 0 -> 0 -> 1 -> None

    # 测试用例 4
    l1 = createList([1])
    l2 = createList([9, 9])
    result4 = addTwoNumbers(l1, l2)
    print("Test case 4:")
    printList(result4)  # 预期输出: 0 -> 0 -> 1 -> None

    # 测试用例 5
    l1 = createList([5])
    l2 = createList([5])
    result5 = addTwoNumbers(l1, l2)
    print("Test case 5:")
    printList(result5)  # 预期输出: 0 -> 1 -> None

# 运行测试用例
test_addTwoNumbers()